package com.century.sjt.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.allinpay.appayassistex.APPayAssistEx;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.adapter.MerchantOrderDetailsAdapter;
import com.century.sjt.entity.BankCard;
import com.century.sjt.entity.ChangeOrderInfo;
import com.century.sjt.entity.MyOrderInfo;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.CustomDialog;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.century.sjt.widget.svpprogresshud.SVProgressHUD;
import com.century.sjt.window.OrderPayPopupWindow;
import com.century.sjt.window.PayPopupWindow;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author:周玲波
 * @Description: 商家、分店订单详情
 * @date : 2016/9/5 15:23
 */
public class MerchantOrderDetailActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.my_order_details_title)
    SjtTitleBar titleBar;
    @BindView(R.id.tv_order_time)
    TextView orderTime;
    @BindView(R.id.tv_order_status)
    TextView orderStatus;
    @BindView(R.id.tv_order_total)
    TextView orderTotal;
    @BindView(R.id.tv_discount)
    TextView diacount;
    @BindView(R.id.tv_discount_total)
    TextView discountTotal;
    @BindView(R.id.tv_order_id)
    TextView  tv_order_id;
    //    @BindView(R.id.tv_home_currency)
//    TextView homeCurrency;
//    @BindView(R.id.tv_total_type)
//    TextView totalType;
//    @BindView(R.id.tv_money_type)
//    TextView moneyType;
//    @BindView(R.id.home_currency_type)
//    TextView  homeCurrencyType;
    @BindView(R.id.item_tv_name)
    TextView consignee;
    @BindView(R.id.item_tv_phome)
    TextView consigneePhone;
    @BindView(R.id.item_tv_address)
    TextView consigneeAddress;
    @BindView(R.id.btn_cancle_order)
    Button cancleOrder;
    @BindView(R.id.btn_pay)
    Button btnPay;
    @BindView(R.id.tv_change_address)
    TextView tvIcon;
    @BindView(R.id.ll_chang_address)
    LinearLayout changAddress;
    @BindView(R.id.ll_order_pay)
    LinearLayout ll_order_pay;
    @BindView(R.id.ll_chang_order)
    LinearLayout ll_chang_order;
    @BindView(R.id.btn_cancle_chang)
    Button btn_cancle_chang;
    @BindView(R.id.btn_chang_order)
    Button btn_chang_order;
    @BindView(R.id.btn_return_of_goods)
    Button btn_return_of_goods;
//    @BindView(R.id.ll_logistics_information)
//     LinearLayout ll_logistics_information;
    @BindView(R.id.ll_discount)
    LinearLayout ll_discount;
//    @BindView(R.id.ll_apply_goods_rejected)
//    LinearLayout ll_apply_goods_rejected;

//    @BindView(R.id.btn_cancle_goods_rejected)//拒绝
//     Button btn_cancle_goods_rejected;
//    @BindView(R.id.btn_apply_goods_rejected)
//    Button btn_apply_goods_rejected;//同意

    String id = null;
    private List<MyOrderInfo> orderIdList;
    private List<MyOrderInfo> goodsList = new ArrayList<>();
    private Context mContext;
    private SVProgressHUD mSVProgressHUD;
    private Handler mHandler;
    private MerchantOrderDetailsAdapter adapter;
    private ListView mListView;
    private SwipeRefreshLayout mSwipeLayout;//刷新组件

    CustomDialog.Builder builder;
    ChangeOrderInfo mInfo = new ChangeOrderInfo();
    Gson gson = new Gson();

    //自定义的弹出框类
    OrderPayPopupWindow menuWindow;
    PayPopupWindow payWindow;
    private String toPayType = "0";

    private List<BankCard> mCardList = new ArrayList<>();//银行卡支付
    private List<BankCard> mMTList = new ArrayList<>();//移动支付

    private String payCardNo = ""; //支付银行卡
    private String balance = "";//账户余额
    private String Status = "0";//判断订单状态
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order_details);
        ButterKnife.bind(this);

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        TipUtil.closeProgressDialog();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 2:
                        goodsList.clear();
                        orderDetails(id);
                        break;
                    case 3:
//                        if(isDataChangeOk) {
//                            mSwipeLayout.setRefreshing(true);
//                            iCurrPage++;
//                            getRecords();
//                        }
                        break;
                }
            }
        };
        initView();
        initEvent();
        initData();
    }

    @Override
    protected void initView() {
        mSVProgressHUD = new SVProgressHUD(this);
        mSVProgressHUD.showWithStatus(getResources().getString(R.string.jiazaizhong));
        mContext = this;
        builder = new CustomDialog.Builder(this);

        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        tvIcon.setTypeface(iconfont);
        titleBar.setLeftIconResource(getResources().getString(R.string.icon_return));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mListView = (ListView) findViewById(R.id.my_order_details_lv);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.activity_list_refesh);
        //ll_logistics_information.setVisibility(View.GONE);
    }

    @Override
    protected void initEvent() {
        cancleOrder.setOnClickListener(this);
        btnPay.setOnClickListener(this);
        changAddress.setOnClickListener(this);
        btn_cancle_chang.setOnClickListener(this);
        btn_chang_order.setOnClickListener(this);
        btn_return_of_goods.setOnClickListener(this);
//        btn_cancle_goods_rejected.setOnClickListener(this);
//        btn_apply_goods_rejected.setOnClickListener(this);


        payWindow = new PayPopupWindow(MerchantOrderDetailActivity.this, "0", "");

        payWindow.setPayWindowListItemClickListener(new PayPopupWindow.PayWindowListItemClickListener() {
            @Override
            public void onItemClick(BankCard message) {
                payCardNo = message.getBankCardNo();
            }

            @Override
            public void onPayTypeClick(String Type) {
                toPayType = Type;
                BuyPay(mInfo);
            }
        });


        adapter = new MerchantOrderDetailsAdapter(MerchantOrderDetailActivity.this, goodsList, mHandler);
        mListView.setAdapter(adapter);
        //长安监听
//        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Log.d("Tag","监听。。。。");
//            }
//        });

        //刷新组件
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        int falg = intent.getIntExtra("falg", 3);

        String orderId = null;
        switch (falg) {
            case 2:
                orderId = intent.getStringExtra("orderId");
                id = orderId;
                orderDetails(orderId);
                break;
            case 3:
                orderId = intent.getStringExtra("orderId");
                id = orderId;
                orderDetails(orderId);
                break;
        }

    }

    /**
     * @Description: 订单详情
     * @author: 周玲波
     * @date: 2016/8/30 17:24
     */
    private void orderDetails(final String orderId) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.orderDetails, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    mSVProgressHUD.dismiss();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {
                        JSONObject data = res.getJSONObject("data");
                        JSONObject receiver = data.getJSONObject("receiver");
                        //discount=data.getString("discount");
                        mInfo.setOrderId(data.getString("orderId"));
                        mInfo.setShopId(data.getString("shopId"));
                        mInfo.setUserId(data.getString("userId"));
                        mInfo.setOrderAmount(data.getString("orderAmount"));
                        mInfo.setDiscountAmount(data.getString("discountAmount"));
                        mInfo.setSettleAmount(data.getString("settleAmount"));
                        mInfo.setDiscount(data.getString("discount"));
                        mInfo.setConsignee(receiver.getString("consignee"));
                        mInfo.setPhone(receiver.getString("phone"));
                        mInfo.setAddress(receiver.getString("address"));

                        setTV(mInfo);

                        titleBar.setTitle(data.getString("shopName"));
                        orderTime.setText(data.getString("orderTime"));

                        orderStatusJudge(data.getString("status"));//判断订单状态

                        if (data.getString("isVip").equals(1)) {
                            diacount.setText(getResources().getString(R.string.text_vip));
                        }
                        //homeCurrencyType.setText(data.getString("settleCurrency"));

                        JSONArray myOrderListist = data.getJSONArray("goodList");
                        for (int i = 0; i < myOrderListist.length(); i++) {
                            JSONObject aData = (JSONObject) myOrderListist.get(i);
                            MyOrderInfo info = new MyOrderInfo();
                            info.setUnitPrice(aData.getString("price"));
                            info.setImage(aData.getString("mainImageUrl"));
                            info.setTotal(aData.getString("amount"));
                            info.setGoodsQuantity(aData.getString("quantity"));
                            info.setGoodId(aData.getString("goodId"));
                            goodsList.add(info);
                        }

                    } else {
                        TipUtil.showToast(message, MerchantOrderDetailActivity.this, 1);
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), MerchantOrderDetailActivity.this, 1);
                }

                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MerchantOrderDetailActivity.this, 1);
                TipUtil.closeProgressDialog();

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderId", orderId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    /**
     * @Description: 订单状态判断
     * @author: 周玲波
     * @date: 2016/9/6 20:01
     */
    private void orderStatusJudge(String status) {
        Log.d("Tag","订单状态"+status);
        String mStatus= null;
        switch (status) {
            case "0"://已撤销
                break;
            case "1"://待支付
                mStatus = getResources().getString(R.string.text_not_pay);
                btn_return_of_goods.setVisibility(View.VISIBLE);
                ll_chang_order.setVisibility(View.GONE);
                ll_order_pay.setVisibility(View.GONE);
                //ll_apply_goods_rejected.setVisibility(View.GONE);
                btn_return_of_goods.setText(getResources().getString(R.string.btn_close));
                break;
            case "2"://已支付（待发货）
                Status="2";
                mStatus = getResources().getString(R.string.text_already_pay);
                btn_return_of_goods.setVisibility(View.VISIBLE);
                ll_chang_order.setVisibility(View.GONE);
                ll_order_pay.setVisibility(View.GONE);
                //ll_apply_goods_rejected.setVisibility(View.GONE);
                btn_return_of_goods.setText(getResources().getString(R.string.btn_send_out_goods));
                break;
            case "3"://已发货（待结算）
                mStatus = getResources().getString(R.string.text_send_out_goods);

                btn_return_of_goods.setVisibility(View.VISIBLE);
                ll_chang_order.setVisibility(View.GONE);
                ll_order_pay.setVisibility(View.GONE);
                //ll_apply_goods_rejected.setVisibility(View.GONE);
                btn_return_of_goods.setText(getResources().getString(R.string.btn_close));
                break;
            case "4"://已完成
                mStatus = getResources().getString(R.string.text_already_complete);
                btn_return_of_goods.setVisibility(View.VISIBLE);
                ll_chang_order.setVisibility(View.GONE);
                ll_order_pay.setVisibility(View.GONE);
                //ll_apply_goods_rejected.setVisibility(View.GONE);
                btn_return_of_goods.setText(getResources().getString(R.string.btn_close));
                break;
            case "5"://退货中
                //this.mStatus = getResources().getString(R.string.text_return_of_goods);
                //ll_apply_goods_rejected.setVisibility(View.VISIBLE);
                //btn_return_of_goods.setVisibility(View.GONE);
               // ll_chang_order.setVisibility(View.GONE);
               // ll_order_pay.setVisibility(View.GONE);


                break;

            case "6"://已退货
               // mStatus = getResources().getString(R.string.text_already_return_goods);

                break;
            case "7"://退款中
                //mStatus = getResources().getString(R.string.text_refund);
                //btn_return_of_goods.setVisibility(View.VISIBLE);
                //ll_apply_goods_rejected.setVisibility(View.GONE);
                //ll_chang_order.setVisibility(View.GONE);
                //ll_order_pay.setVisibility(View.GONE);
                //btn_return_of_goods.setText(getResources().getString(R.string.text_cancle));
                break;
            case "8"://已退款
                //mStatus = getResources().getString(R.string.text_already_refund);
                break;
        }
        orderStatus.setText(mStatus);
    }


    private void setTV(ChangeOrderInfo mInfo) {
        if (mInfo.getOrderAmount().equals("null")) {
            orderTotal.setText("");
        } else {
            orderTotal.setText(mInfo.getOrderAmount());
        }
        discountTotal.setText(mInfo.getDiscountAmount());
        //homeCurrency.setText(mInfo.getSettleAmount());
        if (mInfo.getConsignee().equals("null")) {
            consignee.setText(getResources().getString(R.string.text_chonse_address));
        } else {
            consignee.setText(mInfo.getConsignee());
        }
        if (mInfo.getPhone().equals("null")) {
            consigneePhone.setText("");
        } else {
            consigneePhone.setText(mInfo.getPhone());
        }
        if (mInfo.getAddress().equals("null")) {
            consigneeAddress.setText("");
        } else {
            consigneeAddress.setText(mInfo.getAddress());
        }
        tv_order_id.setText(mInfo.getOrderId());
        if (mInfo.getDiscount()!=null){
            if (mInfo.getDiscount().equals("10")){
                ll_discount.setVisibility(View.GONE);
            }else{
                ll_discount.setVisibility(View.VISIBLE);
            }
        }

    }

    /**
     * @Description: 修改订单
     * @author: 周玲波
     * @date: 2016/8/29 21:11
     */
    private void changeOrder(final List<Map> list, final ChangeOrderInfo info) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.changeOrder, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    goodsList.clear();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {
                        JSONObject data = res.getJSONObject("data");
                        JSONObject receiver = data.getJSONObject("receiver");
                        mInfo.setOrderId(data.getString("orderId"));
                        mInfo.setShopId(data.getString("shopId"));
                        mInfo.setUserId(data.getString("userId"));
                        mInfo.setOrderAmount(data.getString("orderAmount"));
                        mInfo.setDiscountAmount(data.getString("discountAmount"));
                        mInfo.setSettleAmount(data.getString("settleAmount"));
                        mInfo.setConsignee(receiver.getString("consignee"));
                        mInfo.setPhone(receiver.getString("phone"));
                        mInfo.setAddress(receiver.getString("address"));
                        mInfo.setDiscount(data.getString("discount"));
                        setTV(mInfo);
                        titleBar.setTitle(data.getString("shopName"));
                        orderTime.setText(data.getString("orderTime"));
                        if (data.getString("status").equals("0") | data.getString("status").equals("null")) {
                            orderStatus.setText(getResources().getString(R.string.text_not_pay));
                        } else {
                            orderStatus.setText(getResources().getString(R.string.text_already_pay));
                        }
                        if (data.getString("isVip").equals(1)) {
                            diacount.setText(getResources().getString(R.string.text_vip));
                        }
                        //homeCurrencyType.setText(data.getString("settleCurrency"));
                        JSONArray myOrderListist = data.getJSONArray("goodList");
                        for (int i = 0; i < myOrderListist.length(); i++) {
                            JSONObject aData = (JSONObject) myOrderListist.get(i);
                            MyOrderInfo info = new MyOrderInfo();
                            info.setUnitPrice(aData.getString("price"));
                            info.setImage(aData.getString("mainImageUrl"));
                            info.setTotal(aData.getString("amount"));
                            info.setGoodsQuantity(aData.getString("quantity"));
                            info.setRememberQuantity(aData.getString("quantity"));
                            info.setGoodId(aData.getString("goodId"));
                            goodsList.add(info);
                        }
                        TipUtil.showToast(getResources().getString(R.string.text_update_success), MerchantOrderDetailActivity.this, 1);
                        ll_order_pay.setVisibility(View.VISIBLE);
                        ll_chang_order.setVisibility(View.GONE);
                    } else {
                        TipUtil.showToast(message, MerchantOrderDetailActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), MerchantOrderDetailActivity.this, 1);
                }
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MerchantOrderDetailActivity.this, 1);
                TipUtil.closeProgressDialog();

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderId", id);
                map.put("receiver.consignee", info.getConsignee());
                map.put("receiver.phone", info.getPhone());
                map.put("receiver.address", info.getAddress());
                map.put("goods", new Gson().toJson(list));
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }


    /**
     * @Description: 取消订单
     * @author: 周玲波
     * @date: 2016/8/31 10:33
     */
    private void cancleOrder(final String orderId) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.cancleOrder, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {
                        mSVProgressHUD.dismiss();
                        TipUtil.showToast(getResources().getString(R.string.text_cancle_success), MerchantOrderDetailActivity.this, 1);
//                        startActivity(MerchantOrderDetailActivity.this, MyOrderActivity.class);
                        finish();
                    } else {
                        TipUtil.showToast(message, MerchantOrderDetailActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), MerchantOrderDetailActivity.this, 1);
                }
                TipUtil.closeProgressDialog();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MerchantOrderDetailActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderId", orderId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (APPayAssistEx.REQUESTCODE == requestCode) {
            if (null != data) {
                String payRes = null;
                String payAmount = null;
                String payTime = null;
                String payOrderId = null;
                try {
                    JSONObject resultJson = new JSONObject(data.getExtras().getString("result"));
                    payRes = resultJson.getString(APPayAssistEx.KEY_PAY_RES);
                    payAmount = resultJson.getString("payAmount");
                    payTime = resultJson.getString("payTime");
                    payOrderId = resultJson.getString("payOrderId");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (null != payRes && payRes.equals(APPayAssistEx.RES_SUCCESS)) {
                    TipUtil.showToast(getResources().getString(R.string.tab_pay_success), MerchantOrderDetailActivity.this, 1);
                    startActivity(MerchantOrderDetailActivity.this, MyOrderActivity.class);
//                    startActivity(new Intent(MerchantOrderDetailActivity.this, ChatActivity.class).putExtra("userId",mInfo.getUserId()));
//                    showAppayRes("支付成功！");
                } else {
//                    showAppayRes("支付失败！");
                    consumeCancel(mInfo.getOrderId());
                    TipUtil.showToast(getResources().getString(R.string.error_pay_no), MerchantOrderDetailActivity.this, 1);
                }
                Log.d("payResult", "payRes: " + payRes + "  payAmount: " + payAmount + "  payTime: " + payTime + "  payOrderId: " + payOrderId);
            }
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //取消订单
            case R.id.btn_cancle_order:
                builder.setMessage(getResources().getString(R.string.text_sure_cancle_order));
                builder.setPositiveButton(getResources().getString(R.string.text_sure), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        mSVProgressHUD.showWithStatus(getResources().getString(R.string.text_being_cancled));
                        cancleOrder(id);
                    }
                });
                builder.setNegativeButton(getResources().getString(R.string.text_cancle),
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            //支付
            case R.id.btn_pay:
                GetPayType("1", mInfo.getShopId(), mInfo.getDiscountAmount());
                break;
            //取消修改订单
            case R.id.btn_cancle_chang:
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
                ll_order_pay.setVisibility(View.VISIBLE);
                ll_chang_order.setVisibility(View.GONE);
                setTV(mInfo);
                break;
            //确认修改订单
            case R.id.btn_chang_order:
                final List<Map> list = new ArrayList<>();
                for (int i = 0; i < goodsList.size(); i++) {
                    if (!(goodsList.get(i).getGoodsQuantity().equals(goodsList.get(i).getRememberQuantity()))) {
                        Map<String, Object> goodIdMap = new HashMap<>();
                        goodIdMap.put("quantity", Integer.valueOf(goodsList.get(i).getGoodsQuantity()));
                        goodIdMap.put("goodId", goodsList.get(i).getGoodId());
                        list.add(goodIdMap);
                    } else {
                        Map<String, Object> goodIdMap = new HashMap<>();
                        goodIdMap.put("quantity", Integer.valueOf(goodsList.get(i).getGoodsQuantity()));
                        goodIdMap.put("goodId", goodsList.get(i).getGoodId());
                        list.add(goodIdMap);
                    }
                }
                builder.setMessage(getResources().getString(R.string.text_sure_change_order));
                builder.setPositiveButton(getResources().getString(R.string.text_sure), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        changeOrder(list, mInfo);
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton(getResources().getString(R.string.text_cancle),
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            //发货
            case R.id.btn_return_of_goods:

                //跳转到扫描二维码
//                Intent intent = new Intent();
//                intent.setClass(MerchantOrderDetailActivity.this, QRRecordCodeScanActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivityForResult(intent, com.century.sjt.util.Constant.SCANNIN_GREQUEST_CODE);
                if (Status.equals("2")) {
                    Intent intent = new Intent();
                    intent.setClass(MerchantOrderDetailActivity.this, MyOrderEnteringMessage.class);
                    intent.putExtra("orderId", id);
                    intent.putExtra("type", "inputOrder");
                    startActivity(intent);
                }else{
                    finish();
                }
                break;
//            //同意
//            case R.id.btn_apply_goods_rejected:
//                rejectORAgreeSendOutGoods("1");
//
//
//                break;
//            //拒绝
//            case R.id.btn_cancle_goods_rejected:
//                rejectORAgreeSendOutGoods("0");
//
//
//                break;

        }
    }

    /**
     * 获取支付方式
     */
    private void GetPayType(final String Type, final String MerchantId, final String Amount) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.GetPayMethodInfo, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {

                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject aData = res.getJSONObject("data");
                    balance = aData.getString("balance");
//                    tv_Balance.setText(balance);
                    if (code.equals("200")) {//成功
                        mCardList.clear();
                        mMTList.clear();
                        JSONArray cardList = aData.getJSONArray("cardList");
                        JSONArray MTList = aData.getJSONArray("MTList");
                        for (int i = 0; i < cardList.length(); i++) {
                            JSONObject item = (JSONObject) cardList.get(i);
                            BankCard bankCard = new BankCard();
                            bankCard.setPhone(item.getString("phone"));
                            bankCard.setCardName(item.getString("cardName"));
                            bankCard.setBankCardNo(item.getString("bankCardNo"));
                            bankCard.setAvailable(item.getString("available"));
                            bankCard.setLimit(item.getString("limit"));
                            bankCard.setBankCode(item.getString("bankCode"));
                            bankCard.setCardType(item.getString("accountType"));
                            bankCard.setRemarks(item.getString("remarks"));
                            bankCard.setIsActive(item.getString("isActive"));
                            mCardList.add(bankCard);
                        }
                        for (int i = 0; i < MTList.length(); i++) {
                            JSONObject item = (JSONObject) MTList.get(i);
                            BankCard bankCard = new BankCard();
                            bankCard.setPhone(item.getString("phone"));
                            bankCard.setCardName(item.getString("cardName"));
                            bankCard.setBankCardNo(item.getString("bankCardNo"));
                            bankCard.setBankCode(item.getString("bankCode"));
                            bankCard.setCardType(item.getString("accountType"));
                            bankCard.setRemarks(item.getString("remarks"));
                            bankCard.setAvailable(item.getString("available"));
                            bankCard.setLimit(item.getString("limit"));
                            mMTList.add(bankCard);
                        }

                        payWindow.setmCardList(mCardList);
                        payWindow.setmMTList(mMTList);
                        payWindow.setBalance(balance);
                        //显示窗口
                        //设置layout在PopupWindow中显示的位置
                        payWindow.showAtLocation(MerchantOrderDetailActivity.this.findViewById(R.id.paymacth), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service), mContext, 1);
                }

                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("shopId", MerchantId);
                map.put("amount", Amount);
                map.put("type", Type);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);


    }

    //支付
    private void BuyPay(final ChangeOrderInfo aInfo) {
        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        String isCashPwdSet = mainSharedPreferences.getString("isCashPwdSet", "");

        if (isCashPwdSet.equals("1")) {
            switch (toPayType) {
//
                case "0"://余额支付
                    paytoAcoument(aInfo.getDiscount(), aInfo.getDiscountAmount(), aInfo.getOrderAmount(), balance, "3");
                    break;
                case "1"://快捷支付
                    paytoAcoument(aInfo.getDiscount(), aInfo.getDiscountAmount(), aInfo.getOrderAmount(), balance, "1");
                    break;
                case "2"://银行卡支付
                    paytoBankCard(aInfo.getDiscount(), aInfo.getDiscountAmount(), aInfo.getOrderAmount(), payCardNo);
                    break;
                case "3"://其它银行卡支付
                    paytoBankCard(aInfo.getDiscount(), aInfo.getDiscountAmount(), aInfo.getOrderAmount(), payCardNo);
                    break;
                default:
            }
        } else {

//                    跳转设置支付密码界面
            //询问是否取消
            AlertDialog.Builder builder = new AlertDialog.Builder(MerchantOrderDetailActivity.this);
            builder.setTitle(getResources().getString(R.string.text_prompt));
            builder.setMessage(getResources().getString(R.string.text_hint_notset_password));
            builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent intent = new Intent();
                    intent.setClass(MerchantOrderDetailActivity.this, Setting_pwdPayActivity.class);
                    startActivity(intent);
                }
            });
            builder.setNegativeButton(getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setCancelable(false);
            builder.create().show();

        }
    }

    private void paytoBankCard(String discount, String discountAmount, String orderAmount, String BankCard) {
//        Log.e("pay","merchantId"+merchantId+"discount"+discount+"discountAmount"+discountAmount+"orderAmount"+orderAmount+"BankCard"+BankCard);
        payBankCard(mInfo.getShopId(), discount, discountAmount, orderAmount, BankCard);

//        etAccountAmount.setText("");
    }

    private void paytoAcoument(String discount, String discountAmount, String orderAmount, String mBlance, String payType) {
//        Log.e("paytoAcoument", discount + "&" + discountAmount + "&" + orderAmount + "&" + mBlance);

        if (payType.equals("1")) {
            //实例化SelectPicPopupWindow
            menuWindow = new OrderPayPopupWindow(MerchantOrderDetailActivity.this, mInfo.getShopId(), discount, discountAmount, orderAmount, mBlance, payType, payCardNo, id);
            //显示窗口
            //设置layout在PopupWindow中显示的位置
            menuWindow.showAtLocation(MerchantOrderDetailActivity.this.findViewById(R.id.paymacth), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            menuWindow.setPayPwdWindowListItemClickListener(new OrderPayPopupWindow.PayPwdWindowListItemClickListener() {
                @Override
                public void onPassWord(String pwd) {

                }

                @Override
                public boolean onSuccess(boolean message) {
                    if (message) {
                        TipUtil.showToast(getResources().getString(R.string.tab_pay_success), MerchantOrderDetailActivity.this, 1);
                        startActivity(MerchantOrderDetailActivity.this, MyOrderActivity.class);
//                        mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("userId",aMerchant.getUserId()));
                    }
                    return message;
                }
            });
        } else {
            double balance = Double.parseDouble(mBlance);
            double account = Double.parseDouble(orderAmount);
            if (balance == 0 || account > balance) {
                TipUtil.showToast(getResources().getString(R.string.error_balance_not_enough), MerchantOrderDetailActivity.this, 1);
            } else {
                //实例化SelectPicPopupWindow
                menuWindow = new OrderPayPopupWindow(MerchantOrderDetailActivity.this, mInfo.getShopId(), discount, discountAmount, orderAmount, mBlance, payType, payCardNo, id);
                //显示窗口
                //设置layout在PopupWindow中显示的位置
                menuWindow.showAtLocation(MerchantOrderDetailActivity.this.findViewById(R.id.paymacth), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//
                menuWindow.setPayPwdWindowListItemClickListener(new OrderPayPopupWindow.PayPwdWindowListItemClickListener() {
                    @Override
                    public void onPassWord(String pwd) {

                    }

                    @Override
                    public boolean onSuccess(boolean message) {
                        if (message) {
//                            mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("userId",aMerchant.getUserId()));
                        }
                        return message;
                    }
                });
            }

        }


    }

    private void payBankCard(final String MerchantId, final String discount, final String discountAmount, final String orderAmount, final String BankCard) {

//        Log.e("pay",orderAmount+"&"+MerchantId+"&"+discount+"&"+discountAmount);
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, mContext.getResources().getString(R.string.error_please_waitting), MerchantOrderDetailActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ApplyConsume, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("确认支付接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
//                        TipUtil.showToast("支付成功", getActivity(), 1);
                        JSONObject Data = res.getJSONObject("data");
//                        Log.e("text", Data.getString("issuerId") + "&" + Data.getString("tradeNature"));
                        String issuerId = Data.getString("issuerId");
                        String tradeNature = Data.getString("tradeNature");
                        String signType = Data.getString("signType");
                        String orderCurrency = Data.getString("orderCurrency");
                        String version = Data.getString("version");
                        String cardNo = Data.getString("cardNo");
                        String receiveUrl = Data.getString("receiveUrl");
                        String inputCharset = Data.getString("inputCharset");
                        String orderNo = Data.getString("orderNo");
                        String ext1 = Data.getString("ext1");
                        String orderAmount = Data.getString("orderAmount");
                        String signMsg = Data.getString("signMsg");
                        String payType = Data.getString("payType");
                        String merchantId = Data.getString("merchantId");
                        String language = Data.getString("language");
                        String orderDatetime = Data.getString("orderDatetime");
                        String productName = Data.getString("productName");
                        if (!(issuerId == null || issuerId.equals(""))) {
                            if (!(tradeNature == null || tradeNature.equals(""))) {
                                JSONObject paaParams = new JSONObject();
                                try {
                                    paaParams.put("inputCharset", inputCharset);
                                    paaParams.put("receiveUrl", receiveUrl);
                                    paaParams.put("version", version);
                                    paaParams.put("signType", signType);
                                    paaParams.put("merchantId", merchantId);
                                    paaParams.put("orderNo", orderNo);
                                    paaParams.put("orderAmount", orderAmount);
                                    paaParams.put("orderCurrency", orderCurrency);
                                    paaParams.put("orderDatetime", orderDatetime);
                                    paaParams.put("productName", productName);
//                                    paaParams.put("ext1", ext1);
                                    paaParams.put("payType", payType);
//                        paaParams.put("issuerId", "visa");
//                        paaParams.put("tradeNature", "GOODS");
                                    paaParams.put("language", language);
                                    if (!(BankCard.equals("BankCardNo"))) {
                                        paaParams.put("cardNo", BankCard);
                                    } else {
                                        paaParams.put("cardNo", cardNo);
                                    }
                                    paaParams.put("signMsg", signMsg);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                APPayAssistEx.startPay(MerchantOrderDetailActivity.this, paaParams.toString(), Constant.PAYKEY);
                            }
                        } else {
                            APPayAssistEx.startPay(MerchantOrderDetailActivity.this, Data.toString(), Constant.PAYKEY);

                        }

                    } else {//失败
                        TipUtil.showToast(message, MerchantOrderDetailActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service), MerchantOrderDetailActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), MerchantOrderDetailActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("payerId", userId);
                map.put("recieverId", MerchantId);
                map.put("orderAmount", orderAmount);
                map.put("discount", discount);
                map.put("discountAmount", discountAmount);
                map.put("accountAmount", "0");
                map.put("cardAmount", discountAmount);
                map.put("fee", "0");
                map.put("payMethod", "2");
                //                0：普通  1：商品订单
                map.put("orderType", "1");
                map.put("goodsOrderId", id);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        mQueue.add(stringRequest);
    }

    private void consumeCancel(final String orderNo) {
        //显示Progress Dialog
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.GetConsumeCancel, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        Log.e("depositCancel", "订单取消成功");
//                        Log.e("text", Data.getString("issuerId") + "&" + Data.getString("tradeNature"));


                    } else {//失败
//                        TipUtil.showToast(message, WalletRechareActivity.this, 1);
                        TipUtil.log("订单取消失败！", message.toString(), 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
//                    TipUtil.showToast(getResources().getString(R.string.error_service), WalletRechareActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                TipUtil.showToast(getResources().getString(R.string.error_network), WalletRechareActivity.this, 1);
//                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderNo", orderNo);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    /**
     * @Description：拒绝或同意退货
     * @author: 周玲波
     * @date: 2016/9/6 20:43
     */
    private void rejectORAgreeSendOutGoods(final String operate) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.returnGoodConfirm, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {

                    } else {
                        TipUtil.showToast(message, MerchantOrderDetailActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), MerchantOrderDetailActivity.this, 1);
                }
                TipUtil.closeProgressDialog();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MerchantOrderDetailActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderId", id);
                map.put("operate", operate);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

}
